﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Linq.Expressions;
using System.Data.Objects;
using System.Data.Entity.Infrastructure;
using System.Data;

namespace UniSoft.ERP.EntityFramework.Context
{
    public class RepositoryContext<T> where T : class
    {
        public DbContext Context { get; set; }

        public T Create(T entity)
        {
            Context.Entry<T>(entity).State = System.Data.EntityState.Added;
            Context.SaveChanges();

            return entity;
        }

        public T Update(T entity)
        {
            IsAttached(entity);

            Context.Entry<T>(entity).State = System.Data.EntityState.Modified;
            Context.SaveChanges();

            return entity;
        }

        public bool Delete(int id)
        {
            var entity = Context.Set<T>().Find(id);
            Context.Entry<T>(entity).State = System.Data.EntityState.Deleted;
            Context.SaveChanges();

            return true;
        }

        public IQueryable<T> Read()
        {
            return Context.Set<T>();
        }

        public IQueryable<T> Read(Expression<Func<T, bool>> expression)
        {
            return Context.Set<T>().Where(expression);
        }

        private bool IsAttached(T entity)
        {
            var objContext = ((IObjectContextAdapter)Context).ObjectContext;

            var objSet = objContext.CreateObjectSet<T>();
            var entityKey = objContext.CreateEntityKey(objSet.EntitySet.Name, entity);

            object foundEntity = null;
            bool exists;

            try
            {
                exists = objContext.TryGetObjectByKey(entityKey, out foundEntity);
            }
            catch (EntityCommandExecutionException)
            {
                exists = false;
            }

            if (exists)
            {
                objContext.Detach(foundEntity);
            }

            return (exists);
        }
    }
}
